/**
 * AI服务模块 - 提供各种AI功能的接口服务
 * 重构为调用Python AI服务
 */

import { httpPost, httpGet } from "../utils/http";
import ENV_CONFIG from "../config/env";

// AI服务接口定义
export interface AIQuestionGenerationRequest {
  topic: string;
  count: number;
  type: "choice" | "programming" | "analysis" | "fill" | "essay";
  difficulty: "easy" | "medium" | "hard";
  requirements?: string;
  knowledgePoints?: string[];
  targetGrade?: string;
}

// 试卷模板生成请求
export interface AIExamPaperGenerationRequest {
  templateId: string;
  templateName: string;
  paperName: string;
  additionalDescription?: string;
  questionTypes: {
    choice: number;
    programming: number;
    analysis: number;
    fill: number;
    essay: number;
  };
  totalScore: number;
  duration: number;
  difficulty: "简单" | "中等" | "困难";
  subject: string;
  tags: string[];
  knowledgePoints?: string[];
  // 新增字段
  questionRequirements?: {
    choice?: string;
    programming?: string;
    analysis?: string;
    fill?: string;
    essay?: string;
  };
  scoringRules?: {
    choice: number;
    programming: number;
    analysis: number;
    fill: number;
    essay: number;
  };
  // 进度回调
  onProgress?: (progress: number, message: string) => void;
}

// 题目重新生成请求接口
export interface AIQuestionRegenerateRequest {
  questionId: string;
  questionType: string;
  originalContent: string;
  requirements: string;
  templateContext: {
    subject: string;
    difficulty: string;
    knowledgePoints: string[];
  };
}

export interface AIGradingRequest {
  question: string;
  studentAnswer: string;
  standardAnswer: string;
  gradingCriteria?: string[];
}

export interface AIAssistantRequest {
  userRole: "student" | "teacher" | "admin";
  message: string;
  context?: any;
}

export interface AIReminderRequest {
  userId: string;
  userType: "student" | "teacher" | "admin";
  contextData: any;
}

export interface AILessonPlanRequest {
  subject: string;
  topic: string;
  duration: number;
  targetGrade: string;
  objectives: string[];
}

// Python AI服务请求格式
export interface PythonAIChatRequest {
  message: string;
  account_id?: string;
  course_id?: string;
}

export interface PythonAIFileRequest {
  file: File;
  course_id?: string;
  file_id?: string;
  knowledge_point?: string;
  pages?: number;
}

// 角色化提示词配置
export const AI_PROMPTS = {
  student: {
    role: "学习助手",
    systemPrompt:
      "你是一个专业的学习助手，专门帮助学生解决学习问题，提供学习建议和答疑解惑。回答要简洁明了，富有启发性。",
    suggestions: [
      "如何提高学习效率？",
      "这道题的解题思路是什么？",
      "推荐一些学习资源",
      "制定学习计划",
      "如何准备考试？",
    ],
  },
  teacher: {
    role: "教学助手",
    systemPrompt:
      "你是一个资深的教学助手，专门协助教师进行教学设计、学生分析、课程优化等工作。回答要专业且实用。",
    suggestions: [
      "如何设计有效的教学活动？",
      "分析学生学习情况",
      "优化课程结构",
      "制定评估标准",
      "提升课堂互动",
    ],
  },
  admin: {
    role: "管理助手",
    systemPrompt:
      "你是一个专业的教育管理助手，专门协助管理者进行数据分析、决策支持、运营优化等工作。回答要有数据支撑且具有战略眼光。",
    suggestions: [
      "分析平台使用数据",
      "优化管理流程",
      "制定发展策略",
      "评估教学质量",
      "资源配置建议",
    ],
  },
};

// AI智能助手类
export class AIService {
  private pythonAIBaseUrl = ENV_CONFIG.AI_API_BASE_URL || "http://localhost:8000";

  // 获取默认用户信息（从localStorage或其他地方获取）
  private getDefaultUserInfo() {
    try {
      const userStr = localStorage.getItem('user');
      const user = userStr ? JSON.parse(userStr) : null;
      return {
        account_id: user?.id?.toString() || "default_user",
        course_id: user?.currentCourseId?.toString() || "default_course"
      };
    } catch (error) {
      console.warn("获取用户信息失败，使用默认值", error);
      return {
        account_id: "default_user",
        course_id: "default_course"
      };
    }
  }

  // 流式聊天 - 调用Python AI服务
  async chatWithAssistant(
    request: AIAssistantRequest
  ): Promise<{ reply: string; suggestions?: string[] }> {
    try {
      const userInfo = this.getDefaultUserInfo();
      const enhancedMessage = this.enhanceMessageWithRole(request.message, request.userRole);
      
      const response = await fetch(`${this.pythonAIBaseUrl}/api/teach/chat?account_id=${userInfo.account_id}&course_id=${userInfo.course_id}`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          message: enhancedMessage,
        }),
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      // 处理流式响应
      const reader = response.body?.getReader();
      if (!reader) {
        throw new Error("无法获取响应流");
      }

      let fullResponse = "";
      let buffer = "";
      const decoder = new TextDecoder();

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        
        const chunk = decoder.decode(value);
        buffer += chunk;

        // 按行处理SSE数据
        const lines = buffer.split('\n');
        buffer = lines.pop() || ""; // 保留最后一个可能不完整的行

        for (const line of lines) {
          if (line.startsWith('data: ')) {
            try {
              const jsonStr = line.slice(6); // 移除 'data: ' 前缀
              if (jsonStr.trim() === '') continue;
              
              // 移除可能的尾部 ']'
              const cleanJsonStr = jsonStr.replace(/\]$/, '');
              const data = JSON.parse(cleanJsonStr);
              
              if (data.data && typeof data.data === 'string') {
                fullResponse += data.data;
              }
            } catch (e) {
              console.warn('解析SSE数据失败:', line, e);
            }
          }
        }
      }

      return {
        reply: fullResponse || "AI服务暂时无响应",
        suggestions: AI_PROMPTS[request.userRole].suggestions.slice(0, 3),
      };
    } catch (error) {
      console.error("Python AI聊天失败:", error);
      return this.getMockChatResponse(request);
    }
  }

  // 根据角色增强消息
  private enhanceMessageWithRole(message: string, userRole: string): string {
    const validRole = (userRole as keyof typeof AI_PROMPTS) || 'student';
    const roleConfig = AI_PROMPTS[validRole] || AI_PROMPTS.student;
    return `${roleConfig.systemPrompt}\n\n用户问题：${message}`;
  }

  // 生成题目 - 使用文件接口
  async generateQuestions(request: AIQuestionGenerationRequest): Promise<any> {
    try {
      // 构建知识点参数
      const knowledgePoint = request.knowledgePoints?.join(", ") || request.topic;
      
      // 创建一个临时文件来模拟题目生成
      const questionPrompt = `
        主题：${request.topic}
        题目类型：${request.type}
        难度：${request.difficulty}
        数量：${request.count}
        要求：${request.requirements || ""}
        知识点：${knowledgePoint}
      `;
      
      const formData = new FormData();
      const blob = new Blob([questionPrompt], { type: 'text/plain' });
      formData.append('file', blob, 'question_requirements.txt');
      formData.append('knowledge_point', knowledgePoint);

      const response = await fetch(`${this.pythonAIBaseUrl}/api/file/exam`, {
        method: "POST",
        body: formData,
      });

      if (!response.ok) {
        throw new Error("题目生成失败");
      }

      // 处理流式响应
      const reader = response.body?.getReader();
      if (!reader) {
        throw new Error("无法获取响应流");
      }

      let questionsJson = "";
      const decoder = new TextDecoder();

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        
        const chunk = decoder.decode(value);
        questionsJson += chunk;
      }

      try {
        // 提取JSON数据，去除"data: "前缀和可能的markdown代码块标记
        let jsonStr = questionsJson;
        if (jsonStr.includes("data: ")) {
          jsonStr = jsonStr.split("data: ")[1] || jsonStr;
        }
        
        // 去除可能的markdown代码块标记
        jsonStr = jsonStr.replace(/```json\n?/g, "").replace(/```\n?/g, "").trim();
        
        const questions = JSON.parse(jsonStr);
        return { questions };
      } catch (parseError) {
        console.warn("解析题目JSON失败，返回模拟数据", parseError);
        console.warn("原始响应:", questionsJson);
        return this.getMockQuestions(request);
      }
    } catch (error) {
      console.error("AI生成题目失败:", error);
      return this.getMockQuestions(request);
    }
  }

  // 生成题目 - 使用专用接口（独立于智能组卷）
  async generateQuestionsWithDedicatedAPI(request: AIQuestionGenerationRequest): Promise<any> {
    try {
      // 构建知识点参数
      const knowledgePoint = request.knowledgePoints?.join(", ") || request.topic;
      
      // 构建详细的题目生成要求
      const questionPrompt = `
        题目生成要求：
        
        主题：${request.topic}
        题目类型：${request.type}
        难度等级：${request.difficulty}
        生成数量：${request.count}
        目标年级：${request.targetGrade || '大二'}
        知识点：${knowledgePoint}
        特殊要求：${request.requirements || '无特殊要求'}
        
        请根据以上要求生成${request.count}道高质量的${request.type}类型题目。
        题目难度要符合${request.difficulty}等级，内容要围绕${request.topic}主题。
        如果是选择题，请提供4个合理的选项。
        每个题目都要有详细的解析和答案。
      `;
      
      const formData = new FormData();
      const blob = new Blob([questionPrompt], { type: 'text/plain' });
      formData.append('file', blob, 'question_generation.txt');
      formData.append('knowledge_point', knowledgePoint);

      // 使用新的专用接口
      const response = await fetch(`${this.pythonAIBaseUrl}/api/file/generate-questions`, {
        method: "POST",
        body: formData,
      });

      if (!response.ok) {
        throw new Error("题目生成失败");
      }

      // 处理流式响应
      const reader = response.body?.getReader();
      if (!reader) {
        throw new Error("无法获取响应流");
      }

      let questionsJson = "";
      const decoder = new TextDecoder();

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        
        const chunk = decoder.decode(value);
        questionsJson += chunk;
      }

      try {
        // 提取JSON数据，去除"data: "前缀和可能的markdown代码块标记
        let jsonStr = questionsJson;
        if (jsonStr.includes("data: ")) {
          jsonStr = jsonStr.split("data: ")[1] || jsonStr;
        }
        
        // 去除可能的markdown代码块标记
        jsonStr = jsonStr.replace(/```json\n?/g, "").replace(/```\n?/g, "").trim();
        
        const questions = JSON.parse(jsonStr);
        return { questions };
      } catch (parseError) {
        console.warn("解析题目JSON失败，返回模拟数据", parseError);
        console.warn("原始响应:", questionsJson);
        return this.getMockQuestions(request);
      }
    } catch (error) {
      console.error("AI生成题目失败:", error);
      return this.getMockQuestions(request);
    }
  }

  // 根据模板生成完整试卷
  async generateExamPaper(request: AIExamPaperGenerationRequest): Promise<any> {
    try {
      // 进度回调函数
      const updateProgress = (progress: number, message: string) => {
        if (request.onProgress) {
          request.onProgress(progress, message);
        }
      };

      // 开始生成
      updateProgress(5, "正在分析模板要求...");
      await new Promise(resolve => setTimeout(resolve, 500));

      // 构建完整的模板信息JSON
      const templateInfo = {
        templateName: request.templateName,
        paperName: request.paperName,
        description: `基于${request.templateName}的试卷`,
        aiDescription: request.additionalDescription || "",
        totalScore: request.totalScore,
        duration: request.duration,
        difficulty: request.difficulty,
        subject: request.subject,
        tags: request.tags,
        questionTypes: request.questionTypes,
        scoringRules: request.scoringRules || {
          choice: 4,
          programming: 15,
          analysis: 10,
          fill: 3,
          essay: 8
        },
        questionRequirements: request.questionRequirements || {
          choice: "基础知识点考察",
          programming: "编程能力考察",
          analysis: "分析能力考察",
          fill: "基础知识点掌握",
          essay: "综合理解能力"
        },
        additionalDescription: request.additionalDescription || ""
      };

      updateProgress(10, "正在准备AI生成请求...");
      await new Promise(resolve => setTimeout(resolve, 300));

      const examPrompt = JSON.stringify(templateInfo, null, 2);
      
      const formData = new FormData();
      const blob = new Blob([examPrompt], { type: 'text/plain' });
      formData.append('file', blob, 'exam_template.txt');
      formData.append('knowledge_point', request.subject);

      console.log("发送AI生成试卷请求...");
      updateProgress(15, "正在连接AI服务...");
      
      const response = await fetch(`${this.pythonAIBaseUrl}/api/file/exam`, {
        method: "POST",
        body: formData,
      });

      if (!response.ok) {
        throw new Error(`试卷生成失败: ${response.status} ${response.statusText}`);
      }

      console.log("收到响应，开始处理流式数据...");
      updateProgress(20, "AI正在生成试卷内容...");

      // 处理流式响应
      const reader = response.body?.getReader();
      if (!reader) {
        throw new Error("无法获取响应流");
      }

      let examJson = "";
      const decoder = new TextDecoder();
      let timeout = setTimeout(() => {
        console.error("AI生成超时");
        throw new Error("AI生成超时");
      }, 60000); // 60秒超时

      let dataChunks = 0;
      try {
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
          
          const chunk = decoder.decode(value);
          examJson += chunk;
          dataChunks++;
          
          // 根据数据块数量更新进度
          const progress = Math.min(85, 20 + (dataChunks * 5));
          updateProgress(progress, "正在接收AI生成结果...");
          
          console.log("收到数据块:", chunk);
        }
      } finally {
        clearTimeout(timeout);
      }

      console.log("流式数据接收完成，总长度:", examJson.length);
      updateProgress(90, "正在处理生成结果...");

      try {
        // 提取JSON数据
        let jsonStr = examJson;
        console.log("原始响应数据:", examJson);
        
        if (jsonStr.includes("data: ")) {
          jsonStr = jsonStr.split("data: ")[1] || jsonStr;
        }
        
        jsonStr = jsonStr.replace(/```json\n?/g, "").replace(/```\n?/g, "").trim();
        console.log("处理后的JSON字符串:", jsonStr);
        
        const examPaper = JSON.parse(jsonStr);
        console.log("解析后的试卷数据:", examPaper);
        
        // 验证数据结构
        if (!examPaper || !examPaper.questions || !Array.isArray(examPaper.questions)) {
          console.warn("试卷数据结构不正确，返回模拟数据");
          updateProgress(95, "正在生成备用试卷...");
          await new Promise(resolve => setTimeout(resolve, 500));
          return this.getMockExamPaper(request);
        }
        
        // 确保试卷数据包含所有必要字段
        const completeExamPaper = {
          id: `paper_${Date.now()}`,
          templateId: request.templateId,
          templateName: request.templateName,
          name: examPaper.name || request.paperName,
          questions: examPaper.questions,
          totalScore: examPaper.totalScore || request.totalScore,
          duration: examPaper.duration || request.duration,
          createTime: new Date().toISOString(),
          status: "completed" as const,
          generationProgress: 100,
        };
        
        updateProgress(100, "试卷生成完成！");
        await new Promise(resolve => setTimeout(resolve, 300));
        
        console.log("完整的试卷数据:", completeExamPaper);
        return { examPaper: completeExamPaper };
      } catch (parseError) {
        console.warn("解析试卷JSON失败，返回模拟数据", parseError);
        console.error("解析错误详情:", parseError);
        console.error("原始数据:", examJson);
        return this.getMockExamPaper(request);
      }
    } catch (error) {
      console.error("AI生成试卷失败:", error);
      return this.getMockExamPaper(request);
    }
  }

  // 题目重新生成
  async regenerateQuestion(request: AIQuestionRegenerateRequest): Promise<any> {
    try {
      const regeneratePrompt = `
        原题目：${request.originalContent}
        题目类型：${request.questionType}
        重新生成要求：${request.requirements}
        学科：${request.templateContext.subject}
        难度：${request.templateContext.difficulty}
        知识点：${request.templateContext.knowledgePoints.join(", ")}
        
        请根据以上要求重新生成一道题目，要求：
        1. 保持题目类型不变
        2. 符合重新生成要求
        3. 难度适中
        4. 输出格式为JSON，包含以下字段：
           - content: 题目内容
           - answer: 答案
           - analysis: 解析
           - options: 选项数组（仅选择题需要）
           - score: 分值
           - difficulty: 难度
           - knowledge: 知识点数组
           - tags: 标签数组
      `;
      
      const formData = new FormData();
      const blob = new Blob([regeneratePrompt], { type: 'text/plain' });
      formData.append('file', blob, 'regenerate_question.txt');
      formData.append('knowledge_point', request.templateContext.subject);

      const response = await fetch(`${this.pythonAIBaseUrl}/api/file/exam`, {
        method: "POST",
        body: formData,
      });

      if (!response.ok) {
        throw new Error("题目重新生成失败");
      }

      // 处理流式响应
      const reader = response.body?.getReader();
      if (!reader) {
        throw new Error("无法获取响应流");
      }

      let questionJson = "";
      const decoder = new TextDecoder();

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        
        const chunk = decoder.decode(value);
        questionJson += chunk;
      }

      try {
        // 提取JSON数据
        let jsonStr = questionJson;
        if (jsonStr.includes("data: ")) {
          jsonStr = jsonStr.split("data: ")[1] || jsonStr;
        }
        
        jsonStr = jsonStr.replace(/```json\n?/g, "").replace(/```\n?/g, "").trim();
        
        const newQuestion = JSON.parse(jsonStr);
        return { newQuestion };
      } catch (parseError) {
        console.warn("解析重新生成题目JSON失败，返回模拟数据", parseError);
        return this.getMockRegeneratedQuestion(request);
      }
    } catch (error) {
      console.error("AI重新生成题目失败:", error);
      return this.getMockRegeneratedQuestion(request);
    }
  }

  // 作业批改 - 使用评论接口
  async gradeAssignment(
    question: string,
    studentAnswer: string,
    standardAnswer: string
  ): Promise<string> {
    try {
      const comments = `
        题目：${question}
        学生答案：${studentAnswer}
        标准答案：${standardAnswer}
        请对学生答案进行详细批改和评分建议。
      `;

      const response = await fetch(`${this.pythonAIBaseUrl}/api/teach/comment`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ comments }),
      });

      if (!response.ok) {
        throw new Error("批改失败");
      }

      const result = await response.json();
      return result.data || this.getMockGradingFeedback();
    } catch (error) {
      console.error("AI批改失败:", error);
      return this.getMockGradingFeedback();
    }
  }

  // 生成备课计划 - 使用文件大纲接口
  async generateLessonPlan(request: AILessonPlanRequest): Promise<any> {
    try {
      const lessonContent = `
        科目：${request.subject}
        主题：${request.topic}
        时长：${request.duration}分钟
        目标年级：${request.targetGrade}
        教学目标：${request.objectives.join(", ")}
      `;

      const formData = new FormData();
      const blob = new Blob([lessonContent], { type: 'text/plain' });
      formData.append('file', blob, 'lesson_plan.txt');

      const response = await fetch(`${this.pythonAIBaseUrl}/api/file/outline`, {
        method: "POST",
        body: formData,
      });

      if (!response.ok) {
        throw new Error("备课计划生成失败");
      }

      // 处理流式响应
      const reader = response.body?.getReader();
      if (!reader) {
        throw new Error("无法获取响应流");
      }

      let planJson = "";
      const decoder = new TextDecoder();

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        
        const chunk = decoder.decode(value);
        planJson += chunk;
      }

      try {
        return JSON.parse(planJson);
      } catch (parseError) {
        console.warn("解析备课计划JSON失败，返回模拟数据", parseError);
        return this.getMockLessonPlan();
      }
    } catch (error) {
      console.error("AI生成备课计划失败:", error);
      return this.getMockLessonPlan();
    }
  }

  // 智能提醒分析
  async analyzeReminders(request: AIReminderRequest): Promise<{
    reminders: Reminder[];
    insights: string[];
    recommendations: string[];
  }> {
    try {
      const analysisPrompt = `
        用户类型：${request.userType}
        用户ID：${request.userId}
        上下文数据：${JSON.stringify(request.contextData)}
        请分析用户的学习/教学情况，生成智能提醒和建议。
      `;

      const response = await fetch(`${this.pythonAIBaseUrl}/api/teach/comment`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ comments: analysisPrompt }),
      });

      if (!response.ok) {
        throw new Error("提醒分析失败");
      }

      const result = await response.json();
      // 尝试解析AI返回的结构化数据，如果失败则返回模拟数据
      return this.getMockReminders(request);
    } catch (error) {
      console.error("AI提醒分析失败:", error);
      return this.getMockReminders(request);
    }
  }

  // 生成讨论回复
  async generateResponse(
    discussion: any, 
    onStream?: (chunk: string) => void
  ): Promise<string> {
    try {
      const userInfo = this.getDefaultUserInfo();
      const prompt = discussion.enhancedPrompt || `请针对以下讨论内容生成一个专业、有帮助的回复：

标题：${discussion.title}
内容：${discussion.content}

请从教学角度提供有价值的见解和建议。`;

      const response = await fetch(`${this.pythonAIBaseUrl}/api/teach/chat?account_id=${userInfo.account_id}&course_id=${userInfo.course_id}`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          message: prompt,
        }),
      });

      if (!response.ok) {
        throw new Error("生成讨论回复失败");
      }

      // 处理流式响应
      const reader = response.body?.getReader();
      if (!reader) {
        throw new Error("无法获取响应流");
      }

      let fullResponse = "";
      let buffer = "";
      const decoder = new TextDecoder();

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        
        const chunk = decoder.decode(value);
        buffer += chunk;

        // 按行处理SSE数据
        const lines = buffer.split('\n');
        buffer = lines.pop() || ""; // 保留最后一个可能不完整的行

        for (const line of lines) {
          if (line.startsWith('data: ')) {
            try {
              const jsonStr = line.slice(6); // 移除 'data: ' 前缀
              if (jsonStr.trim() === '') continue;
              
              // 移除可能的尾部 ']'
              const cleanJsonStr = jsonStr.replace(/\]$/, '');
              const data = JSON.parse(cleanJsonStr);
              
              if (data.data && typeof data.data === 'string') {
                fullResponse += data.data;
                // 调用流式回调函数
                if (onStream) {
                  onStream(data.data);
                }
              }
            } catch (e) {
              console.warn('解析SSE数据失败:', line, e);
            }
          }
        }
      }

      return fullResponse || this.getMockDiscussionResponse(discussion);
    } catch (error) {
      console.error("AI生成讨论回复失败:", error);
      return this.getMockDiscussionResponse(discussion);
    }
  }

  // 学习行为分析
  async analyzeLearningBehavior(
    studentId: string,
    timeRange: string
  ): Promise<{
    patterns: any[];
    predictions: any[];
    suggestions: string[];
  }> {
    try {
      const analysisPrompt = `
        学生ID：${studentId}
        时间范围：${timeRange}
        请分析学生的学习行为模式，预测学习趋势，并提供改进建议。
      `;

      const response = await fetch(`${this.pythonAIBaseUrl}/api/teach/comment`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ comments: analysisPrompt }),
      });

      if (!response.ok) {
        throw new Error("学习行为分析失败");
      }

      // 返回模拟数据，实际项目中可以进一步解析AI返回的结构化数据
      return this.getMockLearningAnalysis();
    } catch (error) {
      console.error("学习行为分析失败:", error);
      return this.getMockLearningAnalysis();
    }
  }

  // 教学质量评估
  async evaluateTeaching(
    teacherId: string,
    courseId: string
  ): Promise<{
    score: number;
    strengths: string[];
    improvements: string[];
    trends: any[];
  }> {
    try {
      const evaluationPrompt = `
        教师ID：${teacherId}
        课程ID：${courseId}
        请对教师的教学质量进行评估，分析优势和改进点。
      `;

      const response = await fetch(`${this.pythonAIBaseUrl}/api/teach/comment`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ comments: evaluationPrompt }),
      });

      if (!response.ok) {
        throw new Error("教学质量评估失败");
      }

      // 返回模拟数据，实际项目中可以进一步解析AI返回的结构化数据
      return this.getMockTeachingEvaluation();
    } catch (error) {
      console.error("教学质量评估失败:", error);
      return this.getMockTeachingEvaluation();
    }
  }

  // PPT生成功能
  async generatePPT(content: string, pages: number = 3): Promise<Blob> {
    try {
      const pptContent = `content的内容为：${content}   需要${pages}页,需要${pages}页,需要${pages}页,需要${pages}页,需要${pages}页,需要${pages}页,`;
      
      const formData = new FormData();
      const blob = new Blob([pptContent], { type: 'text/plain' });
      formData.append('file', blob, 'ppt_content.txt');
      formData.append('pages', pages.toString());

      const response = await fetch(`${this.pythonAIBaseUrl}/api/file/ppt`, {
        method: "POST",
        body: formData,
      });

      if (!response.ok) {
        throw new Error("PPT生成失败");
      }

      return await response.blob();
    } catch (error) {
      console.error("PPT生成失败:", error);
      throw error;
    }
  }

  async generatePDF(examData: any, pdfType: "exam" | "answer" = "exam"): Promise<Blob> {
    try {
      const formData = new FormData();
      formData.append('exam_data', JSON.stringify(examData));
      formData.append('pdf_type', pdfType);

      const response = await fetch(`${this.pythonAIBaseUrl}/api/file/generate-pdf`, {
        method: "POST",
        body: formData,
      });

      if (!response.ok) {
        throw new Error("PDF生成失败");
      }

      return await response.blob();
    } catch (error) {
      console.error("PDF生成失败:", error);
      throw error;
    }
  }

  // 模拟数据方法保持不变...
  private getMockQuestions(request: AIQuestionGenerationRequest) {
    const mockQuestions = [];
    for (let i = 0; i < request.count; i++) {
      mockQuestions.push({
        id: `q${i + 1}`,
        type: request.type,
        difficulty: request.difficulty,
        title: `${request.topic}相关题目 ${i + 1}`,
        content: `这是一道关于${request.topic}的${request.difficulty === "easy" ? "基础" : request.difficulty === "medium" ? "中等" : "高难度"}题目`,
        options:
          request.type === "choice"
            ? [
                { key: "A", value: "选项A" },
                { key: "B", value: "选项B" },
                { key: "C", value: "选项C" },
                { key: "D", value: "选项D" },
              ]
            : undefined,
        answer: request.type === "choice" ? "A" : "参考答案内容",
        points:
          request.difficulty === "easy"
            ? 5
            : request.difficulty === "medium"
              ? 10
              : 15,
        keywords: request.knowledgePoints || [],
      });
    }
    return { questions: mockQuestions };
  }

  private getMockExamPaper(request: AIExamPaperGenerationRequest) {
    const questions = [];
    let questionId = 1;

    // 生成选择题
    for (let i = 0; i < request.questionTypes.choice; i++) {
      questions.push({
        id: `q${questionId++}`,
        type: "choice",
        content: `基于${request.templateName}的选择题${i + 1}${request.additionalDescription ? `，要求：${request.additionalDescription}` : ""}`,
        answer: "A",
        score: 4,
        options: ["选项A", "选项B", "选项C", "选项D"],
        analysis: "本题考查相关知识点",
        difficulty: request.difficulty,
        knowledge: request.knowledgePoints || [request.subject],
        tags: request.tags,
        canRegenerate: true,
      });
    }

    // 生成编程题
    for (let i = 0; i < request.questionTypes.programming; i++) {
      questions.push({
        id: `q${questionId++}`,
        type: "programming",
        content: `基于${request.templateName}的编程题${i + 1}${request.additionalDescription ? `，要求：${request.additionalDescription}` : ""}`,
        answer: "function solution() {\n  // 编程题答案\n}",
        score: 15,
        analysis: "本题考查编程能力和算法思维",
        difficulty: request.difficulty,
        knowledge: request.knowledgePoints || [request.subject],
        tags: request.tags,
        canRegenerate: true,
      });
    }

    // 生成分析题
    for (let i = 0; i < request.questionTypes.analysis; i++) {
      questions.push({
        id: `q${questionId++}`,
        type: "analysis",
        content: `基于${request.templateName}的分析题${i + 1}${request.additionalDescription ? `，要求：${request.additionalDescription}` : ""}`,
        answer: "分析题答案内容",
        score: 10,
        analysis: "本题考查分析能力和理解深度",
        difficulty: request.difficulty,
        knowledge: request.knowledgePoints || [request.subject],
        tags: request.tags,
        canRegenerate: true,
      });
    }

    // 生成填空题
    for (let i = 0; i < request.questionTypes.fill; i++) {
      questions.push({
        id: `q${questionId++}`,
        type: "fill",
        content: `基于${request.templateName}的填空题${i + 1}${request.additionalDescription ? `，要求：${request.additionalDescription}` : ""}`,
        answer: "填空题答案",
        score: 3,
        analysis: "本题考查基础知识点掌握",
        difficulty: request.difficulty,
        knowledge: request.knowledgePoints || [request.subject],
        tags: request.tags,
        canRegenerate: true,
      });
    }

    // 生成简答题
    for (let i = 0; i < request.questionTypes.essay; i++) {
      questions.push({
        id: `q${questionId++}`,
        type: "essay",
        content: `基于${request.templateName}的简答题${i + 1}${request.additionalDescription ? `，要求：${request.additionalDescription}` : ""}`,
        answer: "简答题答案内容",
        score: 8,
        analysis: "本题考查综合理解和表达能力",
        difficulty: request.difficulty,
        knowledge: request.knowledgePoints || [request.subject],
        tags: request.tags,
        canRegenerate: true,
      });
    }

    return {
      examPaper: {
        id: `paper_${Date.now()}`,
        templateId: request.templateId,
        templateName: request.templateName,
        name: request.paperName,
        questions,
        totalScore: request.totalScore,
        duration: request.duration,
        createTime: new Date().toISOString(),
        status: "completed",
        generationProgress: 100,
      }
    };
  }

  private getMockGradingFeedback(): string {
    const feedbacks = [
      "整体回答思路清晰，对核心概念理解准确。建议在细节论述上更加深入，可以通过具体例子来支撑观点。",
      "答案结构合理，逻辑性强。在技术实现部分表现优秀，但在理论分析方面还有提升空间。",
      "创新思维体现明显，解决方案具有实用性。建议加强对相关技术原理的阐述。",
      "基础概念掌握扎实，分析过程详细。可以考虑从多个角度来论证观点。",
    ];
    return feedbacks[Math.floor(Math.random() * feedbacks.length)];
  }

  private getMockRegeneratedQuestion(request: AIQuestionRegenerateRequest) {
    const typeMap = {
      choice: "选择题",
      programming: "编程题",
      analysis: "分析题",
      fill: "填空题",
      essay: "简答题",
    };

    const baseQuestion = {
      content: `重新生成的${typeMap[request.questionType as keyof typeof typeMap]} - ${request.requirements}`,
      answer: "重新生成的答案",
      analysis: "重新生成的解析",
      score: request.questionType === "choice" ? 4 : 
             request.questionType === "programming" ? 15 :
             request.questionType === "analysis" ? 10 :
             request.questionType === "fill" ? 3 : 8,
      difficulty: request.templateContext.difficulty,
      knowledge: request.templateContext.knowledgePoints,
      tags: request.templateContext.knowledgePoints,
    };

    if (request.questionType === "choice") {
      return {
        newQuestion: {
          ...baseQuestion,
          options: ["选项A", "选项B", "选项C", "选项D"],
        }
      };
    }

    return { newQuestion: baseQuestion };
  }

  private getMockChatResponse(request: AIAssistantRequest): {
    reply: string;
    suggestions?: string[];
  } {
    const roleResponses = {
      student: [
        "我来帮你分析这个问题！首先我们需要理解核心概念，然后通过具体步骤来解决。",
        "这是个很好的问题！让我们从基础开始，逐步深入理解。",
        "学习这个知识点时，建议你先掌握基础理论，再通过实践来巩固。",
      ],
      teacher: [
        "根据我的教学经验，这个教学设计可以通过以下方式优化...",
        "学生在这个知识点上常见的困难包括...建议采用渐进式教学方法。",
        "课堂互动可以通过小组讨论、案例分析等方式来增强。",
      ],
      admin: [
        "从数据分析角度来看，我们可以通过以下指标来评估...",
        "建议制定阶段性目标，并设置相应的评估机制。",
        "优化流程的关键在于标准化和自动化，同时要考虑用户体验。",
      ],
    };

    const responses = roleResponses[request.userRole];
    const reply = responses[Math.floor(Math.random() * responses.length)];

    return {
      reply,
      suggestions: AI_PROMPTS[request.userRole].suggestions.slice(0, 3),
    };
  }

  private getMockLessonPlan() {
    return {
      introduction:
        "本节课将通过理论讲解和实践操作相结合的方式，帮助学生掌握核心概念。",
      objectives: [
        "理解基本概念和原理",
        "掌握实际操作技能",
        "培养分析和解决问题的能力",
      ],
      activities: [
        {
          name: "课程导入",
          duration: 10,
          description: "通过案例引入，激发学习兴趣",
        },
        {
          name: "理论讲解",
          duration: 30,
          description: "系统阐述核心概念和原理",
        },
        {
          name: "实践练习",
          duration: 40,
          description: "动手操作，巩固所学知识",
        },
        {
          name: "总结讨论",
          duration: 10,
          description: "师生互动，答疑解惑",
        },
      ],
      assessment: "采用过程性评价与结果性评价相结合的方式",
      resources: ["教材", "PPT", "实验设备", "在线资源"],
    };
  }

  private getMockReminders(request: AIReminderRequest): {
    reminders: Reminder[];
    insights: string[];
    recommendations: string[];
  } {
    const currentDate = new Date();
    const futureDate = new Date(
      currentDate.getTime() + 7 * 24 * 60 * 60 * 1000
    );

    return {
      reminders: [
        {
          id: "r1",
          type: "homework",
          title: "编程作业提交截止",
          description: "React组件开发作业即将截止，请及时提交",
          priority: "high",
          dueDate: futureDate,
          course: "Web前端开发",
          status: "pending",
        },
        {
          id: "r2",
          type: "exam",
          title: "期中考试安排",
          description: "数据库系统原理期中考试时间已确定",
          priority: "medium",
          dueDate: new Date(currentDate.getTime() + 14 * 24 * 60 * 60 * 1000),
          course: "数据库系统",
          status: "pending",
        },
        {
          id: "r3",
          type: "academic_warning",
          title: "学习预警提醒",
          description: "部分学生出勤率偏低，需要关注",
          priority: "high",
          dueDate: currentDate,
          course: "Web前端开发",
          status: "pending",
        },
      ],
      insights: [
        "近期作业提交率下降10%，建议加强督促",
        "学生对实践类课程参与度较高",
        "期末考试临近，学生咨询频率增加",
      ],
      recommendations: [
        "设置作业提交提醒机制",
        "增加答疑时间安排",
        "提供学习资源推荐",
        "建立学习小组互助机制",
      ],
    };
  }

  private getMockLearningAnalysis() {
    return {
      patterns: [
        {
          type: "study_time",
          data: [8, 6, 7, 5, 9, 8, 6],
          trend: "stable",
        },
        {
          type: "assignment_score",
          data: [85, 78, 92, 88, 86, 90, 87],
          trend: "improving",
        },
      ],
      predictions: [
        {
          metric: "final_score",
          predicted_value: 88,
          confidence: 0.85,
        },
        {
          metric: "pass_probability",
          predicted_value: 0.95,
          confidence: 0.92,
        },
      ],
      suggestions: [
        "保持当前学习节奏，继续加强实践练习",
        "在理论学习方面可以投入更多时间",
        "建议参加同学间的讨论学习",
      ],
    };
  }

  private getMockTeachingEvaluation() {
    return {
      score: Math.floor(Math.random() * 20) + 80, // 80-100分
      strengths: [
        "课程内容设计合理",
        "学生互动积极",
        "知识点讲解清晰",
        "教学方法多样化",
      ],
      improvements: [
        "可以增加更多实践环节",
        "适当调整教学节奏",
        "加强课后反馈机制",
        "丰富教学资源",
      ],
      trends: [
        { month: "9月", score: 85 },
        { month: "10月", score: 88 },
        { month: "11月", score: 91 },
        { month: "12月", score: 89 },
      ],
    };
  }

  private getMockDiscussionResponse(discussion: any): string {
    const responses = [
      `感谢您提出的这个问题！关于"${discussion.title}"，我认为这是一个很有价值的讨论话题。\n\n从教学角度来看，建议您可以从以下几个方面来思考：\n1. 理解核心概念的本质\n2. 结合实际案例进行分析\n3. 多角度探讨解决方案\n\n希望这些建议对您有帮助。如果还有疑问，欢迎继续讨论！`,

      `这是个很好的问题！针对您在"${discussion.title}"中提到的观点，我想分享一些看法：\n\n首先，这个问题涉及到的知识点确实比较复杂，需要我们深入理解。建议您：\n• 查阅相关的理论资料\n• 寻找类似的实践案例\n• 与同学们进行深入交流\n\n期待看到更多精彩的讨论！`,

      `很高兴看到您对"${discussion.title}"的思考！这确实是一个值得深入探讨的话题。\n\n从我的教学经验来看，解决这类问题的关键在于：\n1. 建立清晰的思维框架\n2. 运用批判性思维分析\n3. 理论与实践相结合\n\n希望这些建议能帮助您更好地理解这个问题。继续保持这种积极思考的态度！`,
    ];

    return responses[Math.floor(Math.random() * responses.length)];
  }
}

// 提醒相关接口
export interface Reminder {
  id: string;
  type: "homework" | "exam" | "academic_warning" | "teaching_quality";
  title: string;
  description: string;
  priority: "low" | "medium" | "high" | "urgent";
  dueDate: Date;
  course?: string;
  status: "pending" | "read" | "completed" | "dismissed";
  targetUsers?: string[];
  createdBy?: string;
  metadata?: any;
}

// 创建单例实例
export const aiService = new AIService();

export default aiService;
